package 链表.双指针;


import java.util.Stack;

/**
 * https://leetcode.cn/problems/add-two-numbers/description/?envType=study-plan-v2&envId=top-100-liked
 *
 * https://mp.weixin.qq.com/s?__biz=MzAxODQxMDM0Mw==&mid=2247492022&idx=1&sn=35f6cb8ab60794f8f52338fab3e5cda5&scene=21#wechat_redirect
 */
public class _2_两数相加 {

    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        // 在两条链表上的指针
        if (l1 == null) return l2;
        if (l2 == null) return l1;

        ListNode sential = new ListNode(-1);
        ListNode p = sential;

        Stack<Integer> stack = new Stack<>();

        while (l1 != null || l2 != null) {
            int a = 0;
            if (l1 != null) {
                a = l1.val;
                l1 = l1.next;
            }

            int b = 0;
            if (l2 != null) {
                b = l2.val;
                l2 = l2.next;
            }

            int c = 0;
            if (!stack.isEmpty()) {
                c = stack.pop();
            }

            int res = a + b + c;

            if (res >= 10) {
                stack.push(res / 10);
            }

            p.next = new ListNode(res < 10 ? res : res % 10);
            p = p.next;
        }

        if (!stack.isEmpty()){
            p.next = new ListNode(stack.pop());
        }


        return sential.next;

    }
}
